<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品类别预测系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aos@2.3.4/dist/aos.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- 添加Chart.js datalabels插件 -->
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
    <style>
        :root {
            --primary-color: #5e8ef7;
            --secondary-color: #7b9efc;
            --accent-color: #a0c2ff;
            --light-color: #f8f9fa;
            --dark-color: #4a5568;
            --gray-color: #8d99ae;
            --bg-color: #f9fafe;
            --border-color: #e2e8f0;
        }
        
        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', 'Helvetica Neue', sans-serif;
            background-color: var(--bg-color);
            color: #2d3748;
            min-height: 100vh;
            padding-bottom: 3rem;
            line-height: 1.6;
        }
        
        .header {
            background: linear-gradient(135deg, #a0c2ff 0%, #7b9efc 50%, #5e8ef7 100%);
            color: white;
            padding: 3rem 0 4rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23ffffff" fill-opacity="0.1"/><circle cx="10" cy="10" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="30" cy="10" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="50" cy="10" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="70" cy="10" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="90" cy="10" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="10" cy="30" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="30" cy="30" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="50" cy="30" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="70" cy="30" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="90" cy="30" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="10" cy="50" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="30" cy="50" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="50" cy="50" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="70" cy="50" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="90" cy="50" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="10" cy="70" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="30" cy="70" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="50" cy="70" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="70" cy="70" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="90" cy="70" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="10" cy="90" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="30" cy="90" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="50" cy="90" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="70" cy="90" r="2" fill="%23ffffff" fill-opacity="0.3"/><circle cx="90" cy="90" r="2" fill="%23ffffff" fill-opacity="0.3"/></svg>');
            opacity: 0.3;
        }
        
        .header h1 {
            font-weight: 700;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 1rem;
        }
        
        .header .lead {
            font-weight: 400;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            max-width: 700px;
            margin: 0 auto;
        }
        
        .floating-shapes {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 0;
            overflow: hidden;
        }
        
        .shape {
            position: absolute;
            background-color: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            animation: float 15s infinite linear;
        }
        
        .shape:nth-child(1) {
            width: 80px;
            height: 80px;
            top: 10%;
            left: 10%;
            animation-delay: 0s;
            animation-duration: 25s;
        }
        
        .shape:nth-child(2) {
            width: 60px;
            height: 60px;
            top: 20%;
            right: 15%;
            animation-delay: 2s;
            animation-duration: 30s;
        }
        
        .shape:nth-child(3) {
            width: 100px;
            height: 100px;
            bottom: 10%;
            left: 20%;
            animation-delay: 5s;
            animation-duration: 35s;
        }
        
        .shape:nth-child(4) {
            width: 50px;
            height: 50px;
            bottom: 20%;
            right: 10%;
            animation-delay: 10s;
            animation-duration: 40s;
        }
        
        @keyframes float {
            0% {
                transform: translateY(0) rotate(0deg);
                opacity: 0.8;
            }
            50% {
                transform: translateY(-100px) rotate(180deg);
                opacity: 0.5;
            }
            100% {
                transform: translateY(0) rotate(360deg);
                opacity: 0.8;
            }
        }
        
        .card {
            border-radius: 16px;
            border: 1px solid var(--border-color);
            box-shadow: 0 10px 25px rgba(150, 170, 250, 0.07);
            transition: all 0.35s ease;
            margin-bottom: 2rem;
            overflow: hidden;
            background-color: white;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(150, 170, 250, 0.15);
        }
        
        .card-header {
            background: linear-gradient(90deg, #eef2ff, #f5f7ff);
            color: #1a202c;
            font-weight: 600;
            padding: 1.2rem 1.5rem;
            border-bottom: 1px solid var(--border-color);
            border-radius: 16px 16px 0 0 !important;
        }
        
        .card-body {
            padding: 1.8rem;
        }
        
        .btn-primary {
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            border: none;
            padding: 0.7rem 2rem;
            font-weight: 500;
            border-radius: 8px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            z-index: 1;
        }
        
        .btn-primary::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: all 0.6s ease;
            z-index: -1;
        }
        
        .btn-primary:hover::before {
            left: 100%;
        }
        
        .btn-primary:hover, .btn-primary:focus {
            background: linear-gradient(90deg, var(--secondary-color), var(--primary-color));
            border: none;
            box-shadow: 0 5px 15px rgba(115, 138, 230, 0.4);
            transform: translateY(-2px);
        }
        
        .form-control {
            border-radius: 8px;
            padding: 0.8rem 1.2rem;
            border: 1px solid var(--border-color);
            background-color: white;
            color: #2d3748;
            transition: all 0.3s ease;
            font-size: 1rem;
        }
        
        .form-control:focus {
            box-shadow: 0 0 0 0.25rem rgba(94, 142, 247, 0.25);
            border-color: var(--primary-color);
            background-color: white;
        }
        
        .form-control::placeholder {
            color: #a0aec0;
        }
        
        .form-label {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 0.8rem;
            font-size: 1.05rem;
        }
        
        .product-card {
            position: relative;
            border-radius: 12px;
            overflow: hidden;
            height: 100%;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.05);
            transition: all 0.4s ease;
            border: 1px solid var(--border-color);
            background-color: white;
        }
        
        .product-card:hover {
            transform: translateY(-8px) scale(1.01);
            box-shadow: 0 12px 25px rgba(94, 142, 247, 0.1);
            border-color: var(--accent-color);
        }
        
        .product-img {
            width: 100%;
            height: 200px;
            object-fit: cover;
            transition: all 0.5s ease;
        }
        
        .product-card:hover .product-img {
            transform: scale(1.05);
        }
        
        .product-title {
            background: linear-gradient(to right, rgba(94, 142, 247, 0.9), rgba(123, 158, 252, 0.9));
            color: white;
            position: absolute;
            bottom: 0;
            width: 100%;
            padding: 12px;
            font-size: 0.9rem;
            text-align: center;
            transition: all 0.3s ease;
            font-weight: 500;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .product-details {
            position: absolute;
            bottom: 0;
            width: 100%;
            background: white;
            padding: 10px;
            transform: translateY(100%);
            transition: all 0.3s ease;
            border-top: 1px solid var(--border-color);
        }
        
        .product-card:hover .product-details {
            transform: translateY(0);
        }
        
        .product-card:hover .product-title {
            transform: translateY(-100%);
        }
        
        .detail-item {
            display: flex;
            align-items: center;
            margin-bottom: 6px;
            font-size: 0.85rem;
            color: var(--dark-color);
        }
        
        .detail-item i {
            margin-right: 8px;
            color: var(--primary-color);
            font-size: 0.9rem;
        }
        
        .detail-item:last-child {
            margin-bottom: 0;
        }
        
        .result-container {
            display: none;
            animation: fadeInUp 0.8s ease;
        }
        
        .empty-result {
            text-align: center;
            padding: 3rem 1rem;
            color: #4a5568;
            background-color: rgba(211, 225, 255, 0.1);
            border-radius: 12px;
            border: 1px dashed var(--border-color);
        }
        
        .result-category {
            display: inline-block;
            padding: 0.6rem 1.5rem;
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: 30px;
            font-weight: 700;
            margin-bottom: 1rem;
            box-shadow: 0 4px 12px rgba(94, 142, 247, 0.15);
            transition: all 0.3s ease;
            font-size: 1.1rem;
            letter-spacing: 0.5px;
        }
        
        .result-category:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(94, 142, 247, 0.25);
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 3rem;
        }
        
        .spinner-border {
            color: var(--primary-color);
            width: 3.5rem;
            height: 3.5rem;
        }
        
        .file-input-container {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
        }
        
        .file-input-container input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
        
        .file-input-label {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            border: 2px dashed var(--border-color);
            border-radius: 12px;
            padding: 2.5rem 1rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            background-color: white;
        }
        
        .file-input-label:hover {
            border-color: var(--primary-color);
            background-color: rgba(211, 225, 255, 0.1);
        }
        
        .file-input-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: var(--primary-color);
            transition: all 0.3s ease;
        }
        
        .file-input-label:hover .file-input-icon {
            transform: translateY(-5px);
            color: var(--secondary-color);
        }
        
        .preview-container {
            display: none;
            position: relative;
            margin: 0 auto;
            text-align: center;
            height: 180px;
            overflow: hidden;
            transition: all 0.3s ease;
            border: 2px solid var(--border-color);
            border-radius: 12px;
            background-color: white;
        }
        
        .preview-img {
            max-width: 100%;
            max-height: 100%;
            border-radius: 8px;
            object-fit: contain;
            height: 100%;
            width: 100%;
            padding: 10px;
            transition: all 0.3s ease;
        }
        
        .preview-container:hover .preview-img {
            transform: scale(1.02);
            box-shadow: 0 12px 30px rgba(94, 142, 247, 0.2);
        }
        
        .clear-preview {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: white;
            color: var(--primary-color);
            border-radius: 50%;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
            z-index: 10;
        }
        
        .clear-preview:hover {
            background-color: #f8f9fa;
            color: #dc3545;
            transform: rotate(90deg);
        }
        
        .nav-tabs {
            margin-bottom: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            gap: 0.5rem;
        }
        
        .nav-tabs .nav-link {
            color: #1a202c;
            border: none;
            border-bottom: 3px solid transparent;
            border-radius: 0;
            padding: 1rem 1.5rem;
            font-weight: 600;
            font-size: 1.1rem;
            transition: all 0.3s ease;
            margin-right: 0.5rem;
        }
        
        .nav-tabs .nav-link:hover {
            color: var(--primary-color);
            border-color: rgba(94, 142, 247, 0.3);
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            border-color: var(--primary-color);
            background-color: transparent;
            font-weight: 700;
            font-size: 1.15rem;
        }
        
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .stats-container {
            display: flex;
            justify-content: space-around;
            margin: 2rem 0;
            flex-wrap: wrap;
        }
        
        .stat-item {
            text-align: center;
            padding: 1.5rem;
            border-radius: 12px;
            background-color: white;
            box-shadow: 0 5px 15px rgba(150, 170, 250, 0.1);
            margin: 0.5rem;
            min-width: 200px;
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
        }
        
        .stat-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(150, 170, 250, 0.15);
        }
        
        .stat-number {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: var(--primary-color);
        }
        
        .stat-label {
            color: #4b5563;
            font-weight: 500;
        }
        
        .features-section {
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        
        .feature-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 1.5rem;
            padding: 1.5rem;
            border-radius: 12px;
            background-color: white;
            transition: all 0.3s ease;
            border: 1px solid var(--border-color);
        }
        
        .feature-item:hover {
            box-shadow: 0 10px 20px rgba(150, 170, 250, 0.1);
            transform: translateY(-5px);
        }
        
        .feature-icon {
            font-size: 2rem;
            color: var(--primary-color);
            margin-right: 1rem;
            background-color: rgba(211, 225, 255, 0.2);
            width: 60px;
            height: 60px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .feature-item:hover .feature-icon {
            background-color: var(--primary-color);
            color: white;
            transform: rotate(10deg);
        }
        
        .feature-text h5 {
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: var(--dark-color);
        }
        
        .feature-text p {
            color: #4b5563;
            margin-bottom: 0;
            line-height: 1.6;
        }
        
        .footer {
            background-color: white;
            padding: 2rem 0;
            margin-top: 3rem;
            border-top: 1px solid var(--border-color);
            text-align: center;
            color: var(--gray-color);
        }
        
        @media (max-width: 768px) {
            .header {
                padding: 2rem 0 3rem;
            }
            
            .card-body {
                padding: 1.2rem;
            }
            
            .product-img {
                height: 180px;
            }
            
            .stat-item {
                min-width: 150px;
                padding: 1rem;
            }
            
            .stat-number {
                font-size: 2rem;
            }
        }
        
        /* Make the textarea have a solid background */
        textarea.form-control {
            background-color: white !important;
            color: #2d3748 !important;
            font-weight: 500;
        }
        
        /* Improve text contrast in the results */
        .card-body h5 {
            color: #2d3748;
            font-weight: 600;
        }
        
        /* Custom style for tab text */
        .tab-text {
            font-size: 1.15rem;
            font-weight: 600;
        }
        
        .nav-link.active .tab-text {
            font-weight: 700;
        }
        
        /* Ensure tab spacing is adequate */
        .card-header .nav-tabs {
            margin-bottom: 0;
            padding-top: 0.25rem;
        }
        
        /* Make active tab more prominent */
        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            border-color: var(--primary-color);
            background-color: white;
            font-weight: 700;
            font-size: 1.15rem;
            box-shadow: 0 -3px 10px rgba(0, 0, 0, 0.03);
            border-bottom-width: 3px;
            padding-bottom: 1.1rem;
        }
        
        /* Style the tab content area */
        .tab-content {
            background-color: #ffffff;
            padding: 0.5rem 0;
        }
        
        /* Make icons inside tabs larger */
        .nav-link .bi {
            font-size: 1.25rem;
            vertical-align: -2px;
        }
        
        /* Add these styles */
        .audio-preview-container {
            position: relative;
            margin: 0 auto;
            padding: 1rem;
            text-align: center;
            height: 180px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border: 2px solid var(--border-color);
            border-radius: 12px;
            background-color: white;
            transition: all 0.3s ease;
        }
        
        .audio-preview-container:hover {
            border-color: var(--accent-color);
        }
        
        .audio-preview-container audio {
            max-width: 90%;
        }
        
        /* Make input areas consistent height */
        .file-input-label, .form-control-lg {
            height: 180px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            overflow: hidden;
        }
        
        .file-input-label {
            padding: 2rem 1rem;
        }
        
        textarea.form-control-lg {
            resize: none;
            padding: 1.5rem;
        }
        
        /* Adjust icon size for better vertical alignment */
        .file-input-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: var(--primary-color);
            transition: all 0.3s ease;
        }
        
        /* Ensure content is centered within the input areas */
        .file-input-container {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        /* 图表样式 */
        .chart-container {
            position: relative;
            height: 300px;
            background-color: #192a56;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            border: 1px solid #273c75;
        }
        
        .chart-container:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
        }
        
        .chart-container h6 {
            color: #fff;
            font-weight: 600;
            margin-bottom: 15px;
        }
        
        .analytics-section {
            background-color: #273c75;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #273c75;
        }
        
        .analytics-section h5 {
            color: #fff;
        }
        
        /* 分页样式 */
        .pagination .page-item .page-link {
            color: var(--dark-color);
            border-color: var(--border-color);
            border-radius: 8px;
            margin: 0 3px;
            transition: all 0.2s ease;
        }
        
        .pagination .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
            box-shadow: 0 2px 8px rgba(94, 142, 247, 0.25);
        }
        
        .pagination .page-item .page-link:hover {
            background-color: var(--accent-color);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(94, 142, 247, 0.15);
        }
        
        .pagination .page-item.disabled .page-link {
            color: var(--gray-color);
            background-color: var(--light-color);
            border-color: var(--border-color);
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="floating-shapes">
            <div class="shape"></div>
            <div class="shape"></div>
            <div class="shape"></div>
            <div class="shape"></div>
        </div>
        <div class="container">
            <div class="row">
                <div class="col-12 text-center" data-aos="fade-down">
                    <!-- {{ Add Quick Links Section }} -->
                    <div class="mt-4 mb-3" data-aos="fade-up" data-aos-delay="100" style="display: none;">
                        <span class="text-white me-3">快速搜索:</span>
                        <a href="/?query=蛋白粉" class="btn btn-sm btn-light me-2">
                            <i class="bi bi-lightning-charge-fill me-1"></i>蛋白粉
                        </a>
                        <a href="/?query=胶囊" class="btn btn-sm btn-light">
                            <i class="bi bi-capsule-pill me-1"></i>胶囊
                        </a>
                    </div>
                    <!-- {{ End Add Quick Links Section }} -->
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="row">
            <div class="col-lg-10 offset-lg-1">
                <!-- 主卡片 - 上传页面 -->
                <div class="card" data-aos="fade-up" id="uploadSection">
                    <div class="card-header">
                        <h5 class="mb-0 py-2">商品识别</h5>
                    </div>
                    <div class="card-body">
                        <form id="combinedForm">
                            <div class="row row-cols-1 row-cols-md-3 g-4 mb-4">
                                <div class="col">
                                    <div class="file-input-container h-100">
                                        <label class="file-input-label w-100" for="imageFile" id="dropZone">
                                            <i class="bi bi-cloud-upload file-input-icon"></i>
                                            <span>点击或拖拽上传图片</span>
                                            <small class="text-muted d-block mt-2">支持 JPG、PNG、WebP 格式</small>
                                        </label>
                                        <input type="file" id="imageFile" name="file" accept="image/*" class="form-control">
                                    </div>
                                    <div class="preview-container" id="imagePreview">
                                        <img src="" alt="预览图" class="preview-img" id="previewImg">
                                        <span class="clear-preview" id="clearPreview">
                                            <i class="bi bi-x"></i>
                                        </span>
                                    </div>
                                </div>
                                
                                <div class="col">
                                    <div class="file-input-container h-100">
                                        <label class="file-input-label w-100" for="audioFile" id="audioDropZone">
                                            <i class="bi bi-music-note-beamed file-input-icon"></i>
                                            <span>点击或拖拽上传音频</span>
                                            <small class="text-muted d-block mt-2">支持 MP3、WAV、M4A 格式</small>
                                        </label>
                                        <input type="file" id="audioFile" name="audio" accept="audio/*" class="form-control">
                                    </div>
                                    <div class="audio-preview-container" id="audioPreview" style="display:none;">
                                        <audio id="previewAudio" controls class="w-100 mb-2"></audio>
                                        <span class="clear-preview" id="clearAudioPreview">
                                            <i class="bi bi-x"></i>
                                        </span>
                                    </div>
                                </div>
                                
                                <div class="col">
                                    <div class="h-100">
                                        <textarea class="form-control form-control-lg h-100" id="titleInput" name="text" rows="5" placeholder="请输入商品的标题或描述..."></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="text-center">
                                <button type="submit" class="btn btn-primary btn-lg" id="predictBtn">
                                    <i class="bi bi-search me-2"></i>开始识别
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- 加载指示器 -->
                <div class="loading" id="loadingIndicator" data-aos="fade-up">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-3">正在识别，请稍候...</p>
                </div>
                
                <!-- 结果展示 - 结果页面 -->
                <div class="result-container" id="resultContainer" data-aos="fade-up">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">预测结果</h5>
                            <button class="btn btn-outline-primary btn-sm" id="backToUploadBtn" style="display: none;">
                                <i class="bi bi-arrow-left me-1"></i>返回搜索
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="text-center mb-4" style="display: none;">
                                <h5>预测类别：</h5>
                                <div class="result-category" id="categoryResult"></div>
                            </div>
                            
                            <!-- 统计图表区域 -->
                            <div class="analytics-section mb-4">
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <div class="chart-container">
                                            <h6 class="text-center"></h6>
                                            <canvas id="platformChart"></canvas>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <div class="chart-container">
                                            <h6 class="text-center">交易价格区间</h6>
                                            <canvas id="priceRangeChart"></canvas>
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <div class="chart-container">
                                            <h6 class="text-center">评论分类占比统计</h6>
                                            <canvas id="commentRatioChart"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <h5 class="mb-3">线索商品推荐：</h5>
                            <div class="row" id="similarProducts"></div>
                            
                            <!-- 添加分页控件 -->
                            <div class="d-flex justify-content-center mt-4 mb-3" id="pagination">
                                <nav aria-label="商品分页导航">
                                    <ul class="pagination pagination-md"></ul>
                                </nav>
                            </div>
                            
                            <div class="empty-result" id="emptyResult">
                                <i class="bi bi-emoji-frown" style="font-size: 3rem;"></i>
                                <h5 class="mt-3">未找到同类商品</h5>
                                <p>系统未能找到与该类别相关的同类商品，请尝试其他商品。</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <p>© 2023 商品类别预测系统 | 基于深度学习技术 | Powered by Qwen2.5-VL</p>
        </div>
    </footer>

    <!-- {{ Add Modal HTML Structure }} -->
    <div class="modal fade" id="productDetailModal" tabindex="-1" aria-labelledby="productDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="productDetailModalLabel">商品详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- {{ Add Fake Buttons }} -->
                    <div class="mb-3 text-end">
                        <button type="button" class="btn btn-outline-primary me-2" disabled>
                            <i class="bi bi-shield-check me-1"></i>一键固证
                        </button>
                        <button type="button" class="btn btn-success" disabled>
                             <i class="bi bi-plus-circle me-1"></i>加入线索
                         </button>
                    </div>
                    <!-- {{ End Add Fake Buttons }} -->
                    <table class="table table-bordered table-striped">
                        <tbody>
                            <tr>
                                <th scope="row" style="width: 150px;">商品名称</th>
                                <td id="modalProductName"></td>
                            </tr>
                            <tr>
                                <th scope="row">商品地址</th>
                                <td id="modalProductUrl"></td>
                            </tr>
                            <tr>
                                <th scope="row">商品分类</th>
                                <td id="modalProductCategory"></td>
                            </tr>
                            <tr>
                                <th scope="row">采集时间</th>
                                <td id="modalCollectionTime"></td>
                            </tr>
                            <tr>
                                <th scope="row">店铺名称</th>
                                <td id="modalShopName"></td>
                            </tr>
                            <tr>
                                <th scope="row">店铺地址</th>
                                <td id="modalShopUrl"></td>
                            </tr>
                            <tr>
                                <th scope="row">所属地区编码</th>
                                <td id="modalAreaCode"></td>
                            </tr>
                            <tr>
                                <th scope="row">所属地区名称</th>
                                <td id="modalAreaName"></td>
                            </tr>
                            <tr>
                                <th scope="row">主体（公司）名称</th>
                                <td id="modalCompanyName"></td>
                            </tr>
                            <tr>
                                <th scope="row">法定代表人</th>
                                <td id="modalLegalRep"></td>
                            </tr>
                            <tr>
                                <th scope="row">社会信用代码</th>
                                <td id="modalCreditCode"></td>
                            </tr>
                            <tr>
                                <th scope="row">电商名称</th>
                                <td id="modalPlatformName"></td>
                            </tr>
                            <tr>
                                <th scope="row">电商平台编码</th>
                                <td id="modalPlatformCode"></td>
                            </tr>
                             <tr>
                                <th scope="row">电商平台地址</th>
                                <td id="modalPlatformUrl"></td>
                            </tr>
                            <tr>
                                <th scope="row">经营范围</th>
                                <td id="modalBusinessScope"></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    <!-- {{ End Modal HTML Structure }} -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/aos@2.3.4/dist/aos.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 注册Chart.js datalabels插件
            Chart.register(ChartDataLabels);
            
            // 初始化 AOS 动画库
            AOS.init({
                duration: 800,
                easing: 'ease-in-out',
                once: true
            });
            
            // 获取DOM元素
            const combinedForm = document.getElementById('combinedForm');
            const imageFile = document.getElementById('imageFile');
            const titleInput = document.getElementById('titleInput');
            const previewImg = document.getElementById('previewImg');
            const imagePreview = document.getElementById('imagePreview');
            const clearPreview = document.getElementById('clearPreview');
            const loadingIndicator = document.getElementById('loadingIndicator');
            const resultContainer = document.getElementById('resultContainer');
            const categoryResult = document.getElementById('categoryResult');
            const similarProducts = document.getElementById('similarProducts');
            const emptyResult = document.getElementById('emptyResult');
            const dropZone = document.getElementById('dropZone');
            const paginationElement = document.getElementById('pagination');
            
            // 分页配置
            let allProducts = [];
            const productsPerPage = 6;
            let currentPage = 1;
            
            // 获取音频相关DOM元素
            const audioFile = document.getElementById('audioFile');
            const audioPreview = document.getElementById('audioPreview');
            const previewAudio = document.getElementById('previewAudio');
            const clearAudioPreview = document.getElementById('clearAudioPreview');
            const audioDropZone = document.getElementById('audioDropZone');
            
            // 拖放上传功能
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, preventDefaults, false);
            });
            
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            ['dragenter', 'dragover'].forEach(eventName => {
                dropZone.addEventListener(eventName, highlight, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, unhighlight, false);
            });
            
            function highlight() {
                dropZone.classList.add('bg-light');
            }
            
            function unhighlight() {
                dropZone.classList.remove('bg-light');
            }
            
            dropZone.addEventListener('drop', handleDrop, false);
            
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    imageFile.files = files;
                    handleFileSelect({target: {files: files}});
                }
            }
            
            // 图片预览
            imageFile.addEventListener('change', handleFileSelect);
            
            function handleFileSelect(e) {
                if (e.target.files.length > 0) {
                    const file = e.target.files[0];
                    
                    // 验证文件类型
                    if (!file.type.match('image.*')) {
                        alert('请选择图片文件！');
                        return;
                    }
                    
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        previewImg.src = e.target.result;
                        imagePreview.style.display = 'block';
                        document.querySelector('.col:first-child .file-input-container').style.display = 'none';
                        previewImg.classList.add('preview-animation');
                        
                        // 移除动画类
                        setTimeout(() => {
                            previewImg.classList.remove('preview-animation');
                        }, 500);
                    };
                    
                    reader.readAsDataURL(file);
                }
            }
            
            // 清除预览
            clearPreview.addEventListener('click', function() {
                imageFile.value = '';
                imagePreview.style.display = 'none';
                document.querySelector('.col:first-child .file-input-container').style.display = 'block';
            });
            
            // 音频拖放上传功能
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                audioDropZone.addEventListener(eventName, preventDefaults, false);
            });
            
            ['dragenter', 'dragover'].forEach(eventName => {
                audioDropZone.addEventListener(eventName, function() {
                    audioDropZone.classList.add('bg-light');
                }, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                audioDropZone.addEventListener(eventName, function() {
                    audioDropZone.classList.remove('bg-light');
                }, false);
            });
            
            audioDropZone.addEventListener('drop', function(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    audioFile.files = files;
                    handleAudioSelect({target: {files: files}});
                }
            }, false);
            
            // 音频预览
            audioFile.addEventListener('change', handleAudioSelect);
            
            function handleAudioSelect(e) {
                if (e.target.files.length > 0) {
                    const file = e.target.files[0];
                    
                    // 验证文件类型
                    if (!file.type.match('audio.*')) {
                        showToast('请选择音频文件！', 'warning');
                        return;
                    }
                    
                    const audioURL = URL.createObjectURL(file);
                    previewAudio.src = audioURL;
                    audioPreview.style.display = 'block';
                    document.querySelector('.col:nth-child(2) .file-input-container').style.display = 'none';
                }
            }
            
            // 清除音频预览
            clearAudioPreview.addEventListener('click', function() {
                audioFile.value = '';
                audioPreview.style.display = 'none';
                previewAudio.src = '';
                document.querySelector('.col:nth-child(2) .file-input-container').style.display = 'block';
            });
            
            // 图表实例
            let platformChart = null;
            let priceRangeChart = null;
            let commentRatioChart = null;
            
            // 修改组合表单提交
            combinedForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                if (!imageFile.files.length && !titleInput.value.trim() && !audioFile.files.length) {
                    showToast('请上传图片、音频或输入商品标题', 'warning');
                    return;
                }
                
                const formData = new FormData();
                if (imageFile.files.length) {
                    formData.append('file', imageFile.files[0]);
                }
                
                if (audioFile.files.length) {
                    formData.append('audio', audioFile.files[0]);
                }
                
                if (titleInput.value.trim()) {
                    formData.append('text', titleInput.value.trim());
                }
                
                submitPrediction('/predict', formData);
            });
            
            // 提交预测请求
            function submitPrediction(url, formData) {
                // 显示加载状态
                loadingIndicator.style.display = 'block';
                uploadSection.style.display = 'none';
                resultContainer.style.display = 'none';
                
                // 如果图表已存在，先销毁
                destroyCharts();
                
                fetch(url, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络请求失败');
                    }
                    return response.json();
                })
                .then(data => {
                    // 显示类别结果
                    categoryResult.textContent = data.category;
                    categoryResult.style.animation = 'pulse 0.5s ease';
                    
                    // 存储所有产品数据
                    allProducts = data.similar_products || [];
                    
                    // 显示相似商品
                    if (allProducts.length > 0) {
                        emptyResult.style.display = 'none';
                        
                        // 重置分页状态
                        currentPage = 1;
                        
                        // 显示当前页的商品
                        displayProductsForPage(currentPage);
                        
                        // 设置分页控件
                        setupPagination(allProducts.length, productsPerPage);
                        
                        // 绘制统计图表
                        if (data.analytics) {
                            createCharts(data.analytics);
                        } else {
                            // 如果后端未返回分析数据，则从商品数据生成
                            const analytics = generateAnalyticsFromProducts(allProducts);
                            createCharts(analytics);
                        }
                        
                        // 重新初始化AOS动画
                        setTimeout(() => {
                            AOS.refresh();
                        }, 100);
                        
                    } else {
                        similarProducts.innerHTML = '';
                        paginationElement.style.display = 'none';
                        emptyResult.style.display = 'block';
                    }
                    
                    // 显示结果容器，隐藏上传区域
                    resultContainer.style.display = 'block';
                    uploadSection.style.display = 'none';
                    
                    showToast('识别成功！', 'success');
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('请求失败，请稍后重试', 'error');
                    // 出错时显示上传区域
                    uploadSection.style.display = 'block';
                })
                .finally(() => {
                    // 隐藏加载状态
                    loadingIndicator.style.display = 'none';
                    
                    // 移除类别动画
                    setTimeout(() => {
                        categoryResult.style.animation = '';
                    }, 500);
                });
            }
            
            // 显示指定页的商品
            function displayProductsForPage(page) {
                // 清空当前商品显示区
                similarProducts.innerHTML = '';

                // 计算当前页的起始和结束索引
                const startIndex = (page - 1) * productsPerPage;
                const endIndex = Math.min(startIndex + productsPerPage, allProducts.length);

                // 获取当前页的商品
                const currentPageProducts = allProducts.slice(startIndex, endIndex);

                // {{ Modify Product Card Generation for Modal }}
                // Check if the current category requires a modal pop-up
                const currentCategory = categoryResult.textContent;
                const isProteinPowder = currentCategory === '蛋白粉';
                const isCapsule = currentCategory === '胶囊'; // Added check for '胶囊'

                // 显示当前页的商品
                currentPageProducts.forEach((product, index) => {
                    const productCardWrapper = document.createElement('div'); 
                    productCardWrapper.className = 'col-md-4 col-sm-6 mb-4 product-card-wrapper'; 
                    productCardWrapper.setAttribute('data-aos', 'fade-up');
                    productCardWrapper.setAttribute('data-aos-delay', (index * 100).toString());

                    // Add modal trigger attributes if it's '蛋白粉' OR '胶囊'
                    const modalAttributes = (isProteinPowder || isCapsule) 
                        ? 'data-bs-toggle="modal" data-bs-target="#productDetailModal" style="cursor: pointer;"'
                        : '';

                    // Create the product card element
                    const productCard = document.createElement('div');
                    productCard.className = 'product-card h-100';
                    
                    // Store product data for modal use
                    if (isProteinPowder || isCapsule) {
                        productCard.setAttribute('data-bs-toggle', 'modal');
                        productCard.setAttribute('data-bs-target', '#productDetailModal');
                        productCard.style.cursor = 'pointer';
                        // Store the entire product object as JSON
                        productCard.setAttribute('data-product-info', JSON.stringify(product));
                    }
                    
                    productCard.innerHTML = `
                        <img src="${product.image_url}" alt="${product.title}" class="product-img">
                        <div class="product-title">${product.title}</div>
                        <div class="product-details">
                            <div class="detail-item"><i class="bi bi-tag-fill"></i> ¥${product.price}</div>
                            <div class="detail-item"><i class="bi bi-shop"></i> ${product.platform}</div>
                            <div class="detail-item"><i class="bi bi-chat-dots-fill"></i> ${product.comment}</div>
                        </div>
                    `;
                    
                    productCardWrapper.appendChild(productCard);
                    similarProducts.appendChild(productCardWrapper);
                });
                // {{ End Modify Product Card Generation for Modal }}
            }
            
            // 设置分页控件
            function setupPagination(totalItems, itemsPerPage) {
                const totalPages = Math.ceil(totalItems / itemsPerPage);
                const paginationList = paginationElement.querySelector('ul.pagination');
                paginationList.innerHTML = '';
                
                // 只有一页或没有内容时不显示分页
                if (totalPages <= 1) {
                    paginationElement.style.display = 'none';
                    return;
                }
                
                paginationElement.style.display = 'flex';
                
                // 上一页按钮
                const prevItem = document.createElement('li');
                prevItem.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
                prevItem.innerHTML = `<a class="page-link" href="#" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a>`;
                prevItem.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (currentPage > 1) {
                        goToPage(currentPage - 1);
                    }
                });
                paginationList.appendChild(prevItem);
                
                // 生成页码按钮
                const maxPagesToShow = 5;
                let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
                let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
                
                if (endPage - startPage + 1 < maxPagesToShow) {
                    startPage = Math.max(1, endPage - maxPagesToShow + 1);
                }
                
                // 第一页按钮（如果不在范围内）
                if (startPage > 1) {
                    const firstPageItem = document.createElement('li');
                    firstPageItem.className = 'page-item';
                    firstPageItem.innerHTML = `<a class="page-link" href="#">1</a>`;
                    firstPageItem.addEventListener('click', function(e) {
                        e.preventDefault();
                        goToPage(1);
                    });
                    paginationList.appendChild(firstPageItem);
                    
                    // 如果第一页和起始页之间有间隔，添加省略号
                    if (startPage > 2) {
                        const ellipsisItem = document.createElement('li');
                        ellipsisItem.className = 'page-item disabled';
                        ellipsisItem.innerHTML = `<a class="page-link" href="#">&hellip;</a>`;
                        paginationList.appendChild(ellipsisItem);
                    }
                }
                
                // 添加页码按钮
                for (let i = startPage; i <= endPage; i++) {
                    const pageItem = document.createElement('li');
                    pageItem.className = `page-item ${i === currentPage ? 'active' : ''}`;
                    pageItem.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                    pageItem.addEventListener('click', function(e) {
                        e.preventDefault();
                        goToPage(i);
                    });
                    paginationList.appendChild(pageItem);
                }
                
                // 如果结束页和最后一页之间有间隔，添加省略号
                if (endPage < totalPages - 1) {
                    const ellipsisItem = document.createElement('li');
                    ellipsisItem.className = 'page-item disabled';
                    ellipsisItem.innerHTML = `<a class="page-link" href="#">&hellip;</a>`;
                    paginationList.appendChild(ellipsisItem);
                }
                
                // 最后一页按钮（如果不在范围内）
                if (endPage < totalPages) {
                    const lastPageItem = document.createElement('li');
                    lastPageItem.className = 'page-item';
                    lastPageItem.innerHTML = `<a class="page-link" href="#">${totalPages}</a>`;
                    lastPageItem.addEventListener('click', function(e) {
                        e.preventDefault();
                        goToPage(totalPages);
                    });
                    paginationList.appendChild(lastPageItem);
                }
                
                // 下一页按钮
                const nextItem = document.createElement('li');
                nextItem.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
                nextItem.innerHTML = `<a class="page-link" href="#" aria-label="Next"><span aria-hidden="true">&raquo;</span></a>`;
                nextItem.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (currentPage < totalPages) {
                        goToPage(currentPage + 1);
                    }
                });
                paginationList.appendChild(nextItem);
            }
            
            // 跳转到指定页
            function goToPage(page) {
                currentPage = page;
                displayProductsForPage(currentPage);
                
                // 更新分页控件状态
                setupPagination(allProducts.length, productsPerPage);
                
                // 滚动到商品区域顶部
                similarProducts.scrollIntoView({ behavior: 'smooth', block: 'start' });
                
                // 刷新动画
                AOS.refresh();
            }
            
            // 添加返回按钮功能
            document.getElementById('backToUploadBtn').addEventListener('click', function() {
                resultContainer.style.display = 'none';
                uploadSection.style.display = 'block';
                // 重置表单
                combinedForm.reset();
                // 清除预览
                imagePreview.style.display = 'none';
                document.querySelector('.col:first-child .file-input-container').style.display = 'block';
                audioPreview.style.display = 'none';
                previewAudio.src = '';
                document.querySelector('.col:nth-child(2) .file-input-container').style.display = 'block';
                // 清空产品数据
                allProducts = [];
                // {{ Update Back Button Navigation }}
                // Navigate to the base URL without query parameters
                window.history.pushState({}, document.title, "/");
                // {{ End Update Back Button Navigation }}
            });
            
            // 从商品数据生成统计分析
            function generateAnalyticsFromProducts(products) {
                // 平台分布
                const platforms = {};
                // 价格区间分布
                const priceRanges = {
                    '[0-50]': 0,
                    '[50-100]': 0,
                    '[100-150]': 0,
                    '[150-200]': 0,
                    '[200-250]': 0,
                    '[250-300]': 0,
                    '[300-350]': 0,
                    '[350-400]': 0,
                    '[400-450]': 0,
                    '[450-500]': 0
                };
                // 评论分类占比
                const comments = {
                    '积极': 0,
                    '中立': 0,
                    '消极': 0
                };
                
                products.forEach(product => {
                    // 统计平台
                    if (platforms[product.platform]) {
                        platforms[product.platform]++;
                    } else {
                        platforms[product.platform] = 1;
                    }
                    
                    // 统计价格区间
                    const price = parseInt(product.price);
                    if (price <= 50) priceRanges['[0-50]']++;
                    else if (price <= 100) priceRanges['[50-100]']++;
                    else if (price <= 150) priceRanges['[100-150]']++;
                    else if (price <= 200) priceRanges['[150-200]']++;
                    else if (price <= 250) priceRanges['[200-250]']++;
                    else if (price <= 300) priceRanges['[250-300]']++;
                    else if (price <= 350) priceRanges['[300-350]']++;
                    else if (price <= 400) priceRanges['[350-400]']++;
                    else if (price <= 450) priceRanges['[400-450]']++;
                    else priceRanges['[450-500]']++;
                    
                    // 统计评论类型
                    if (comments[product.comment] !== undefined) {
                        comments[product.comment]++;
                    }
                });
                
                // 扩充数据到2000个商品
                const analytics = {
                    platforms,
                    priceRanges,
                    comments
                };
                
                // 如果商品数量不足2000，按比例扩充数据
                if (products.length > 0 && products.length < 2000) {
                    return scaleAnalyticsData(analytics, products.length, 2000);
                }
                
                return analytics;
            }
            
            // 按比例扩充数据
            function scaleAnalyticsData(analytics, actualCount, targetCount) {
                const scaleFactor = targetCount / actualCount;
                
                // 扩充平台数据
                const scaledPlatforms = {};
                Object.keys(analytics.platforms).forEach(platform => {
                    scaledPlatforms[platform] = Math.round(analytics.platforms[platform] * scaleFactor);
                });
                
                // 扩充价格区间数据
                const scaledPriceRanges = {};
                Object.keys(analytics.priceRanges).forEach(range => {
                    scaledPriceRanges[range] = Math.round(analytics.priceRanges[range] * scaleFactor);
                });
                
                // 扩充评论数据
                const scaledComments = {};
                Object.keys(analytics.comments).forEach(comment => {
                    scaledComments[comment] = Math.round(analytics.comments[comment] * scaleFactor);
                });
                
                return {
                    platforms: scaledPlatforms,
                    priceRanges: scaledPriceRanges,
                    comments: scaledComments,
                    isScaled: true,
                    originalCount: actualCount,
                    scaledCount: targetCount,
                    scaleFactor: scaleFactor
                };
            }
            
            // 销毁已有图表
            function destroyCharts() {
                if (platformChart) {
                    platformChart.destroy();
                    platformChart = null;
                }
                if (priceRangeChart) {
                    priceRangeChart.destroy();
                    priceRangeChart = null;
                }
                if (commentRatioChart) {
                    commentRatioChart.destroy();
                    commentRatioChart = null;
                }
            }
            
            // 创建统计图表
            function createCharts(analytics) {
                // 平台分布图表
                const platformCtx = document.getElementById('platformChart').getContext('2d');
                const platformLabels = Object.keys(analytics.platforms);
                const platformData = Object.values(analytics.platforms);
                
                // 确定标题显示
                let titleText = '各平台商品数量统计';
                if (analytics.isScaled) {
                    titleText = '各平台商品数量统计';
                }
                
                platformChart = new Chart(platformCtx, {
                    type: 'bar',
                    data: {
                        labels: platformLabels,
                        datasets: [{
                            label: '商品数量',
                            data: platformData,
                            backgroundColor: '#00a8ff',
                            borderWidth: 0,
                            borderRadius: 4,
                            barThickness: 40,
                            maxBarThickness: 40
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                position: 'top',
                                labels: {
                                    boxWidth: 12,
                                    padding: 15,
                                    color: '#fff'
                                }
                            },
                            title: {
                                display: true,
                                text: titleText,
                                color: '#fff',
                                font: {
                                    size: 16
                                }
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return `数量: ${context.raw}`;
                                    }
                                }
                            },
                            // 使用datalabels插件显示数据标签
                            datalabels: {
                                color: '#ffffff',
                                anchor: 'end',
                                align: 'top',
                                formatter: function(value) {
                                    return value;
                                },
                                font: {
                                    weight: 'bold',
                                    size: 12
                                },
                                padding: {
                                    top: 5
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: {
                                    drawBorder: false,
                                    color: 'rgba(255, 255, 255, 0.1)'
                                },
                                ticks: {
                                    color: '#fff',
                                    callback: function(value) {
                                        // 如果数据量大，使用K单位简化显示
                                        if (value >= 1000) {
                                            return (value / 1000) + 'K';
                                        }
                                        return value;
                                    }
                                }
                            },
                            x: {
                                grid: {
                                    display: false
                                },
                                ticks: {
                                    autoSkip: false,
                                    maxRotation: 0,
                                    minRotation: 0,
                                    color: '#fff',
                                    font: {
                                        size: 8
                                    },
                                    padding: 5,
                                    callback: function(value) {
                                        const label = this.getLabelForValue(value);
                                        // Split at the hyphen and create a proper line break
                                        return label.split('-').join('\n-');
                                    }
                                }
                            }
                        }
                    }
                });
                
                // 价格区间分布图表
                const priceRangeCtx = document.getElementById('priceRangeChart').getContext('2d');
                
                // 动态调整价格区间
                const dynamicPriceRanges = adjustPriceRanges(analytics.priceRanges);
                const priceRangeLabels = Object.keys(dynamicPriceRanges);
                const priceRangeData = Object.values(dynamicPriceRanges);
                
                priceRangeChart = new Chart(priceRangeCtx, {
                    type: 'bar',
                    data: {
                        labels: priceRangeLabels,
                        datasets: [{
                            label: '商品数量',
                            data: priceRangeData,
                            backgroundColor: '#00a8ff',
                            borderWidth: 0,
                            borderRadius: 4,
                            barThickness: 20
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                position: 'top',
                                labels: {
                                    boxWidth: 12,
                                    padding: 15,
                                    color: '#fff'
                                }
                            },
                            title: {
                                display: false,
                                text: '交易价格区间',
                                color: '#fff',
                                font: {
                                    size: 16
                                }
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return `数量: ${context.raw}`;
                                    }
                                }
                            },
                            // 使用datalabels插件显示数据标签
                            datalabels: {
                                color: '#ffffff',
                                anchor: 'end',
                                align: 'top',
                                formatter: function(value) {
                                    // 如果数据量大，使用K单位简化显示
                                    if (value >= 1000) {
                                        return (value / 1000).toFixed(1) + 'K';
                                    }
                                    return value;
                                },
                                font: {
                                    weight: 'bold',
                                    size: 12
                                },
                                padding: {
                                    top: 5
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: {
                                    drawBorder: false,
                                    color: 'rgba(255, 255, 255, 0.1)'
                                },
                                ticks: {
                                    color: '#fff',
                                    callback: function(value) {
                                        if (value >= 1000) {
                                            return (value / 1000) + 'K';
                                        }
                                        return value;
                                    }
                                }
                            },
                            x: {
                                grid: {
                                    display: false
                                },
                                ticks: {
                                    autoSkip: false,
                                    maxRotation: 0,
                                    minRotation: 0,
                                    color: '#fff',
                                    font: {
                                        size: 8
                                    },
                                    padding: 5,
                                    callback: function(value) {
                                        const label = this.getLabelForValue(value);
                                        // Split at the hyphen and create a proper line break
                                        return label.split('-').join('\n-');
                                    }
                                }
                            }
                        }
                    }
                });
                
                // 评论分类占比图表
                const commentRatioCtx = document.getElementById('commentRatioChart').getContext('2d');
                const commentLabels = Object.keys(analytics.comments);
                const commentData = Object.values(analytics.comments);
                
                // 计算总数以便在图表下方添加文本标签
                const commentsTotal = commentData.reduce((acc, val) => acc + val, 0);
                
                commentRatioChart = new Chart(commentRatioCtx, {
                    type: 'pie',
                    data: {
                        labels: commentLabels,
                        datasets: [{
                            data: commentData,
                            backgroundColor: [
                                '#1AA7EC',  // 积极 - 天蓝色
                                '#64B5F6',  // 中立 - 浅蓝色
                                '#0D47A1'   // 消极 - 深蓝色
                            ],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    boxWidth: 15,
                                    padding: 15,
                                    color: '#fff'
                                }
                            },
                            title: {
                                display: false,
                                text: '评论分类占比统计',
                                color: '#fff',
                                font: {
                                    size: 16
                                }
                            },
                            datalabels: {
                                color: '#ffffff',
                                formatter: function(value, context) {
                                    const total = context.dataset.data.reduce((acc, data) => acc + data, 0);
                                    const percentage = Math.round((value / total) * 100);
                                    return percentage + '%';
                                },
                                font: {
                                    weight: 'bold',
                                    size: 12
                                }
                            }
                        }
                    }
                });
                
                // 添加图表右侧的积极、中立、消极统计数据
                const chartContainer = document.querySelector('.col-md-6:nth-child(2) .chart-container');
                // 移除现有的统计信息(如果有)
                const existingStats = chartContainer.querySelector('.comment-stats');
                if (existingStats) {
                    chartContainer.removeChild(existingStats);
                }
                
                const statsDiv = document.createElement('div');
                statsDiv.className = 'comment-stats';
                statsDiv.style.position = 'absolute';
                statsDiv.style.right = '10px';
                statsDiv.style.top = '50px';
                statsDiv.style.color = '#fff';
                statsDiv.style.textAlign = 'left';
                statsDiv.style.fontSize = '14px';
                
                let statsHtml = '';
                commentLabels.forEach((label, index) => {
                    const value = commentData[index];
                    let valueDisplay = value;
                    if (value >= 1000) {
                        valueDisplay = (value / 1000).toFixed(1) + 'K';
                    }
                    statsHtml += `${label}: ${valueDisplay}<br>`;
                });
                
                let totalDisplay = commentsTotal;
                if (commentsTotal >= 1000) {
                    totalDisplay = (commentsTotal / 1000).toFixed(1) + 'K';
                }
                
                statsHtml += `总计: ${totalDisplay}`;
                
                statsDiv.innerHTML = statsHtml;
                chartContainer.appendChild(statsDiv);
            }
            
            // 改进的动态调整价格区间函数
            function adjustPriceRanges(originalRanges) {
                // 获取原始数据
                const originalData = Object.entries(originalRanges);
                
                // 如果数据点太少，不需要调整
                if (originalData.length <= 5) return originalRanges;
                
                // 计算总商品数
                const totalProducts = originalData.reduce((sum, [_, count]) => sum + count, 0);
                
                // 如果总商品数过小，不需要调整
                if (totalProducts < 100) return originalRanges;
                
                // 找出最大值和它所在的区间
                let maxCount = 0;
                let dominantRange = '';
                let maxRangeIndex = -1;
                
                originalData.forEach(([range, count], index) => {
                    if (count > maxCount) {
                        maxCount = count;
                        dominantRange = range;
                        maxRangeIndex = index;
                    }
                });
                
                // 如果最大值占比过高(超过总量的50%)，需要细分该区间
                if (maxCount > totalProducts * 0.5) {
                    // 提取价格范围的上下限
                    const matches = dominantRange.match(/\[(\d+)-(\d+)\]/);
                    if (matches) {
                        const min = parseInt(matches[1]);
                        const max = parseInt(matches[2]);
                        const span = max - min;
                        
                        // 不管价格跨度多大，都细分该区间
                        // 细分为更多子区间，使数据分布更均匀
                        const numSegments = Math.min(10, Math.ceil(maxCount / 200)); // 根据数据量决定分段数
                        const segmentSize = Math.ceil(span / numSegments);
                        
                        // 创建新的价格区间映射
                        const refinedRanges = {};
                        
                        // 保留其他原始区间
                        originalData.forEach(([range, count], index) => {
                            if (range !== dominantRange) {
                                refinedRanges[range] = count;
                            }
                        });
                        
                        // 根据实际数据分布在主导区间内部细分
                        // 假设数据在区间内均匀分布，按比例分配
                        for (let i = 0; i < numSegments; i++) {
                            const start = min + (i * segmentSize);
                            const end = (i === numSegments - 1) ? max : min + ((i + 1) * segmentSize - 1);
                            
                            // 按比例分配数量
                            const segmentCount = Math.floor(maxCount / numSegments);
                            refinedRanges[`[${start}-${end}]`] = segmentCount;
                        }
                        
                        // 确保总数保持一致
                        const allocatedCount = Math.floor(maxCount / numSegments) * numSegments;
                        const remainder = maxCount - allocatedCount;
                        
                        // 将余数分配到最后一个区间
                        if (remainder > 0) {
                            const lastKey = `[${min + ((numSegments - 1) * segmentSize)}-${max}]`;
                            refinedRanges[lastKey] += remainder;
                        }
                        
                        return refinedRanges;
                    }
                }
                
                // 处理其他情况：如果数据分布极不均衡但不是单一区间占主导
                // 根据数据量重新划分区间
                
                // 提取所有价格范围边界值
                const boundaries = [];
                originalData.forEach(([range, _]) => {
                    const matches = range.match(/\[(\d+)-(\d+)\]/);
                    if (matches) {
                        boundaries.push(parseInt(matches[1]));
                        boundaries.push(parseInt(matches[2]));
                    }
                });
                
                if (boundaries.length > 0) {
                    const minPrice = Math.min(...boundaries);
                    const maxPrice = Math.max(...boundaries);
                    
                    // 重新均匀划分区间
                    const equalRanges = {};
                    const step = Math.ceil((maxPrice - minPrice) / 10);
                    
                    for (let i = 0; i < 10; i++) {
                        const start = minPrice + (i * step);
                        const end = (i === 9) ? maxPrice : minPrice + ((i + 1) * step - 1);
                        equalRanges[`[${start}-${end}]`] = 0;
                    }
                    
                    // 重新分配计数
                    // 这里需要一种方法来估计每个新区间应该包含多少商品
                    // 简化处理：假设原始区间内数据均匀分布，按比例分配
                    originalData.forEach(([range, count]) => {
                        const matches = range.match(/\[(\d+)-(\d+)\]/);
                        if (matches && count > 0) {
                            const rangeStart = parseInt(matches[1]);
                            const rangeEnd = parseInt(matches[2]);
                            const rangeSize = rangeEnd - rangeStart;
                            
                            // 对于每个原始区间，将其计数分配到重叠的新区间
                            Object.keys(equalRanges).forEach(newRange => {
                                const newMatches = newRange.match(/\[(\d+)-(\d+)\]/);
                                if (newMatches) {
                                    const newStart = parseInt(newMatches[1]);
                                    const newEnd = parseInt(newMatches[2]);
                                    
                                    // 计算重叠部分
                                    const overlapStart = Math.max(rangeStart, newStart);
                                    const overlapEnd = Math.min(rangeEnd, newEnd);
                                    
                                    if (overlapStart <= overlapEnd) {
                                        // 有重叠，按重叠比例分配计数
                                        const overlapSize = overlapEnd - overlapStart + 1;
                                        const proportion = overlapSize / rangeSize;
                                        equalRanges[newRange] += Math.round(count * proportion);
                                    }
                                }
                            });
                        }
                    });
                    
                    return equalRanges;
                }
                
                // 如果不需要特殊处理，返回原始区间
                return originalRanges;
            }
            
            // 数字动画效果
            function animateValue(id, start, end, duration) {
                const obj = document.getElementById(id);
                if (!obj) return;
                
                let startTimestamp = null;
                const step = (timestamp) => {
                    if (!startTimestamp) startTimestamp = timestamp;
                    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
                    let value = Math.floor(progress * (end - start) + start);
                    
                    if (id === 'accuracyRate') {
                        obj.innerHTML = value + '%';
                    } else {
                        obj.innerHTML = value.toLocaleString();
                    }
                    
                    if (progress < 1) {
                        window.requestAnimationFrame(step);
                    }
                };
                window.requestAnimationFrame(step);
            }
            
            // 显示提示信息
            function showToast(message, type = 'info') {
                // 创建toast元素
                const toast = document.createElement('div');
                toast.className = `toast-notification toast-${type}`;
                toast.textContent = message;
                document.body.appendChild(toast);
                
                // 显示
                setTimeout(() => {
                    toast.classList.add('show');
                }, 10);
                
                // 自动关闭
                setTimeout(() => {
                    toast.classList.remove('show');
                    setTimeout(() => {
                        document.body.removeChild(toast);
                    }, 300);
                }, 3000);
            }
            
            // 添加toast样式
            const style = document.createElement('style');
            style.textContent = `
                .toast-notification {
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    padding: 12px 20px;
                    border-radius: 8px;
                    color: white;
                    font-weight: 500;
                    z-index: 9999;
                    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
                    transform: translateY(-20px);
                    opacity: 0;
                    transition: all 0.3s ease;
                }
                
                .toast-notification.show {
                    transform: translateY(0);
                    opacity: 1;
                }
                
                .toast-success {
                    background-color: #4caf50;
                }
                
                .toast-error {
                    background-color: #f44336;
                }
                
                .toast-warning {
                    background-color: #ff9800;
                }
                
                .toast-info {
                    background-color: var(--primary-color);
                }
                
                .preview-animation {
                    animation: scale-in 0.3s ease;
                }
                
                @keyframes scale-in {
                    from { transform: scale(0.8); opacity: 0; }
                    to { transform: scale(1); opacity: 1; }
                }
            `;
            document.head.appendChild(style);

            // {{ Add URL Query Parameter Handling }}
            // Check for URL query parameters on page load
            const urlParams = new URLSearchParams(window.location.search);
            const queryText = urlParams.get('query');

            if (queryText && queryText.trim() !== '') {
                // If a query parameter exists, trigger prediction automatically
                const formData = new FormData();
                formData.append('text', queryText.trim());
                // Optionally set the title input visually
                titleInput.value = queryText.trim(); 
                // Submit the prediction
                // Use a small timeout to ensure the initial UI is rendered before hiding/showing elements
                setTimeout(() => {
                    submitPrediction('/predict', formData);
                }, 100); 
            }
            // {{ End URL Query Parameter Handling }}

            // {{ Add Modal Population Logic }}
            // 定义字段映射关系：模态框字段ID -> JSON字段名
            const fieldMapping = {
                'modalProductName': ['title', 'product_name', 'name'],
                'modalProductUrl': ['url', 'product_url', 'link'],
                'modalProductCategory': ['category', 'product_category', 'type'],
                'modalCollectionTime': ['collection_time', 'created_at', 'timestamp'],
                'modalShopName': ['shop_name', 'store_name', 'seller'],
                'modalShopUrl': ['shop_url', 'store_url', 'seller_url'],
                'modalAreaCode': ['area_code', 'region_code', 'location_code'],
                'modalAreaName': ['area_name', 'region_name', 'location'],
                'modalCompanyName': ['company_name', 'business_name', 'enterprise_name'],
                'modalLegalRep': ['legal_representative', 'legal_rep', 'representative'],
                'modalCreditCode': ['credit_code', 'social_credit_code', 'business_code'],
                'modalPlatformName': ['platform', 'platform_name', 'site'],
                'modalPlatformCode': ['platform_code', 'site_code'],
                'modalPlatformUrl': ['platform_url', 'site_url'],
                'modalBusinessScope': ['business_scope', 'scope', 'business_range']
            };

            const productDetailModal = document.getElementById('productDetailModal');
            if (productDetailModal) {
                productDetailModal.addEventListener('show.bs.modal', function (event) {
                    // 获取触发模态框的元素
                    const triggerElement = event.relatedTarget;
                    
                    // 尝试从触发元素获取产品数据
                    let productData = null;
                    if (triggerElement && triggerElement.hasAttribute('data-product-info')) {
                        try {
                            productData = JSON.parse(triggerElement.getAttribute('data-product-info'));
                        } catch (e) {
                            console.error('Error parsing product data:', e);
                        }
                    }
                    
                    // 获取所有模态框表格行
                    const modalTableRows = productDetailModal.querySelectorAll('tbody tr');
                    
                    if (productData) {
                        // 根据JSON数据动态填充模态框
                        populateModalFromData(productData, modalTableRows);
                    } else {
                        // 如果没有产品数据，使用原有的硬编码逻辑作为后备
                        const currentCategory = categoryResult.textContent;
                        populateModalWithFallbackData(currentCategory, modalTableRows);
                    }
                });
            }
            
            // 根据JSON数据填充模态框
            function populateModalFromData(productData, modalTableRows) {
                // 获取模态框的表格体
                const modalTableBody = productDetailModal.querySelector('tbody');
                
                // 清空现有的表格内容
                modalTableBody.innerHTML = '';
                

                
                // 遍历JSON中的所有字段
                Object.keys(productData).forEach(key => {
                    const value = productData[key];
                    
                    // 跳过空值、null、undefined
                    if (value === null || value === undefined || value === '') {
                        return;
                    }
                    
                    // 跳过复杂对象和数组（可选，根据需要调整）
                    if (typeof value === 'object' && value !== null) {
                        return;
                    }
                    
                    // 创建表格行
                    const row = document.createElement('tr');
                    
                    // 创建标题单元格 - 直接使用原始key
                    const headerCell = document.createElement('th');
                    headerCell.setAttribute('scope', 'row');
                    headerCell.style.width = '150px';
                    headerCell.textContent = key;
                    
                    // 创建内容单元格 - 直接使用原始value
                    const contentCell = document.createElement('td');
                    
                    // 只对URL进行特殊处理，其他都直接显示原始值
                    if (typeof value === 'string' && (value.startsWith('http://') || value.startsWith('https://'))) {
                        contentCell.innerHTML = `<a href="${value}" target="_blank">${value}</a>`;
                    } else {
                        contentCell.textContent = value;
                    }
                    
                    // 组装行
                    row.appendChild(headerCell);
                    row.appendChild(contentCell);
                    modalTableBody.appendChild(row);
                });
                
                // 如果没有任何字段，显示提示信息
                if (modalTableBody.children.length === 0) {
                    const row = document.createElement('tr');
                    const cell = document.createElement('td');
                    cell.setAttribute('colspan', '2');
                    cell.style.textAlign = 'center';
                    cell.style.color = '#666';
                    cell.textContent = '暂无详细信息';
                    row.appendChild(cell);
                    modalTableBody.appendChild(row);
                }
            }
            

            
            // 后备数据填充（原有的硬编码逻辑）
            function populateModalWithFallbackData(currentCategory, modalTableRows) {
                // 首先隐藏所有行
                modalTableRows.forEach(row => {
                    row.style.display = 'none';
                });
                
                if (currentCategory === '蛋白粉') {
                    // 显示并填充蛋白粉的硬编码数据
                    showAndFillField('modalProductName', '诺特兰德动植物三重蛋白粉中老年蛋白粉营养粉');
                    showAndFillField('modalProductUrl', '<a href="https://you.163.com/item/detail?id=1231645" target="_blank">https://you.163.com/item/detail?id=1231645</a>', true);
                    showAndFillField('modalProductCategory', '保健食品类');
                    showAndFillField('modalCollectionTime', '2024-10-19 08:48:37');
                    showAndFillField('modalShopName', '诺特兰德官方旗舰店');
                    showAndFillField('modalShopUrl', '<a href="https://shop589538478.taobao.com" target="_blank">https://shop589538478.taobao.com</a>', true);
                    showAndFillField('modalAreaCode', '250000');
                    showAndFillField('modalAreaName', '山东省');
                    showAndFillField('modalCompanyName', '诺特兰德有限公司');
                    showAndFillField('modalLegalRep', '王慧');
                    showAndFillField('modalCreditCode', '91370126MA7MGXM234');
                    showAndFillField('modalPlatformName', '淘宝');
                    showAndFillField('modalPlatformCode', 'P0000007');
                    showAndFillField('modalPlatformUrl', '<a href="https://www.taobao.com" target="_blank">https://www.taobao.com</a>', true);
                    showAndFillField('modalBusinessScope', '生产经营');
                } else if (currentCategory === '胶囊') {
                    // 显示并填充胶囊的硬编码数据
                    showAndFillField('modalProductName', '奥利司他胶囊减肥药排油丸瘦腰瘦肚子减脂减肥减重');
                    showAndFillField('modalProductUrl', '<a href="https://you.163.com/item/detail?id=1231645" target="_blank">https://you.163.com/item/detail?id=1231645</a>', true);
                    showAndFillField('modalProductCategory', '保健食品类');
                    showAndFillField('modalCollectionTime', '2024-11-19 08:48:37');
                    showAndFillField('modalShopName', '舒尔佳方旗舰店');
                    showAndFillField('modalShopUrl', '<a href="https://shop230737679.taobao.com" target="_blank">https://shop230737679.taobao.com</a>', true);
                    showAndFillField('modalAreaCode', '100000');
                    showAndFillField('modalAreaName', '北京市');
                    showAndFillField('modalCompanyName', '舒尔佳有限公司');
                    showAndFillField('modalLegalRep', '王辉');
                    showAndFillField('modalCreditCode', '91370126MA7MGXM234');
                    showAndFillField('modalPlatformName', '淘宝');
                    showAndFillField('modalPlatformCode', 'P0000007');
                    showAndFillField('modalPlatformUrl', '<a href="https://www.taobao.com" target="_blank">https://www.taobao.com</a>', true);
                    showAndFillField('modalBusinessScope', '生产经营');
                }
            }
            
            // 显示并填充字段的辅助函数
            function showAndFillField(fieldId, value, isHtml = false) {
                const element = document.getElementById(fieldId);
                if (element) {
                    const row = element.closest('tr');
                    if (row) {
                        row.style.display = '';
                        if (isHtml) {
                            element.innerHTML = value;
                        } else {
                            element.textContent = value;
                        }
                    }
                }
            }
            // {{ End Modal Population Logic }}
        });
    </script>
</body>
</html> 